<?php

namespace App\Modules\Common;


use App\Library\Rank\AbstractSingleRank;
use App\Modules\Order\Models\Order;
use App\Modules\Rebate\Models\Rebate;
use App\Modules\User\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;

class PartnerNumberRank extends AbstractSingleRank
{
    protected static $key = "partner:number_ranking";

    public static function setKey($prefix)
    {
        self::$key = "partner:number_ranking:{$prefix}";
    }

    public static function increaseAll($id, $step = 1)
    {
        self::setKey('quarterly');
        self::increase($id, $step = 1);

        self::setKey('annual');
        self::increase($id, $step = 1);
    }

    public static function flush()
    {
        self::setKey('quarterly');
        Redis::del(static::$key);

        self::setKey('annual');
        Redis::del(static::$key);
    }

    public static function refresh()
    {
        static::flush();
        self::multi(function () {
            Order::query()
                ->join('users', 'users.id', '=', 'orders.referrer_id')
                ->where('orders.referrer_level', 2)
                ->where('orders.status', Order::STATUS_PAID)
                ->where('orders.created_at', '>', now()->startOfYear()->toDateString())
                ->where('users.level', 2)
                ->orderBy('orders.id')
                ->select('orders.*')
                ->each(function ($item) {
                    self::setKey('annual');
                    self::increase($item->referrer_id, 1);
                    if ($item->created_at > now()->startOfQuarter()->toDateTimeString()) {
                        self::setKey('quarterly');
                        self::increase($item->referrer_id, 1);
                    }
                });
        });
    }
}
